﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WF.Common;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WF.Web
{
    public class BasePage : System.Web.UI.Page
    {
        #region properties
        private bool isRebind = false;
        /// <summary>
        /// 是否重新绑定（对应表单的<input type=hidden id=hidIsRebind name=hidIsRebind>控件）

        /// </summary>
        public bool IsRebind
        {
            get { return isRebind; }
            set { isRebind = value; }
        }
        private WF.Common.UserProfile currentUser;
        public UserProfile CurrentUser
        {
            get
            {
                SessionManager sm = new SessionManager();
                return sm.CurrentUser;
            }
        }
        #endregion

        protected override void OnInit(EventArgs e)
        {
            try
            {
                this.isRebind = Convert.ToBoolean(this.Request["hidIsRebind"]);
            }
            catch
            {
                this.isRebind = false;
            }
            base.OnInit(e);
        }

        #region ShowMessage & ExceptionHandle
        public void ShowMessage(string vDesc)
        {
            this.ShowMessage(vDesc, false, false);
        }

        protected void ShowMessage(string vDesc, bool vReturnValue)
        {
            this.ShowMessage(vDesc, false, vReturnValue);
        }

        protected void ShowMessage(string vDesc, bool vCloseWindow, bool vReturnValue)
        {
            WF.Helper.ShowMessage(this, vDesc, vCloseWindow, vReturnValue);
        }

        protected void ShowOpenWindowMessage(string vDesc, bool vCloseWindow, bool vReturnValue, string clientID)
        {
            WF.Helper.ShowOpenWindowMessage(this, vDesc, vCloseWindow, vReturnValue, clientID);
        }

        public void ShowMessage(Exception ex)
        {
            this.ShowMessage(ex.Message, false, false);
        }

        protected void ShowMessage(Exception ex, bool vReturnValue)
        {
            this.ShowMessage(ex.Message, false, vReturnValue);
        }

        protected void ShowMessage(Exception ex, bool vCloseWindow, bool vReturnValue)
        {
            this.ShowMessage(ex.Message, vCloseWindow, vReturnValue);
        }

        protected void ShowOpenWindowMessage(Exception ex, bool vCloseWindow, bool vReturnValue, string clientID)
        {
            this.ShowOpenWindowMessage(ex.Message, vCloseWindow, vReturnValue, clientID);
        }

        public void ShowAjaxMessage(string vDesc)
        {
            WF.Helper.ShowAjaxMessage(this, vDesc, false, false);
        }

        public void ShowAjaxMessage(string vDesc, bool vCloseWindow, bool vReturnValue)
        {
            WF.Helper.ShowAjaxMessage(this, vDesc, vCloseWindow, vReturnValue);
        }

        public void ShowAjaxMessage(Exception ex)
        {
            WF.Helper.ShowAjaxMessage(this, ex, false, false);
        }

        protected void ShowModalDialog(System.Web.UI.Page vPage, string url, string feature, string vClickObjectClientID)
        {
            WF.Helper.ShowModalDialog(vPage, url, feature, vClickObjectClientID);
        }

        public void OpenPopupWindow(string url, string width, string height)
        {
            WF.Helper.OpenPopupWindow(this, url, width, height);
        }

        public void WindowClose(bool vReturnValue)
        {
            WF.Helper.WindowClose(this, vReturnValue);
        }

        public void WindowClose(bool vReturnValue, string alertMessage)
        {
            WF.Helper.WindowClose(this, vReturnValue, alertMessage);
        }

        public void WindowClose(string vReturnValue)
        {
            WF.Helper.WindowClose(this, vReturnValue);
        }

        public void RefreshLeftFrame()
        {
            WF.Helper.RefreshLeftFrame(this);
        }
        #endregion

        #region export to excel
        protected void ExportDataGridExToExcel(System.Web.UI.WebControls.ListView lstView, string excelFileName)
        {
            //如果文件名为中文，必须编码为UTF8
            excelFileName = System.Web.HttpUtility.UrlEncode(excelFileName, System.Text.Encoding.UTF8);

            System.Web.HttpContext curContext = System.Web.HttpContext.Current;

            System.IO.StringWriter strWriter = null;
            System.Web.UI.HtmlTextWriter htmlWriter = null;
            //bool allowPaging, allowSorting, pagerStyleVisible;

            if (lstView != null)
            {
                curContext.Response.Clear();
                curContext.Response.Buffer = false;
                curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
                //curContext.Response.ContentEncoding   =   System.Text.Encoding.GetEncoding("GB2312");

                curContext.Response.Charset = "";
                curContext.Response.AppendHeader("Content-Disposition", "online;filename=" + excelFileName + ".xls");
                curContext.Response.ContentType = "application/vnd.ms-excel";


                strWriter = new System.IO.StringWriter();
                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
                //对于排序的datagridex,先要关掉分页和排序功能 2007.07.13 Added by liuyj.ce
                //allowPaging = lstView.AllowPaging;
                //allowSorting = lstView.AllowSorting;
                //pagerStyleVisible = dgData.PagerStyle.Visible;//原来GRID的属性,moidified by liu on 2007.07.30

                //if (allowPaging)
                //    dgData.AllowPaging = false;
                //if (allowSorting)
                //    dgData.AllowSorting = false;
                //if (pagerStyleVisible)
                //    dgData.PagerStyle.Visible = false;
                //if (allowPaging || allowSorting || pagerStyleVisible)
                //    dgData.BindData();

                //如果listview中有服务端控件，需要把它们隐藏
                this.SetControlVisible(lstView, false);
                lstView.RenderControl(htmlWriter);
                curContext.Response.Write(strWriter.ToString());
                curContext.Response.End();
                //如果listview中有服务端控件，需要把它们显示
                this.SetControlVisible(lstView, true);

                //if (allowPaging)
                //    dgData.AllowPaging = allowPaging;
                //if (allowSorting)
                //    dgData.AllowSorting = allowSorting;
                //if (pagerStyleVisible)
                //    dgData.PagerStyle.Visible = pagerStyleVisible;
                //if (allowPaging || allowSorting || pagerStyleVisible)
                //    dgData.BindData();
                //dgData.BindData();
            }
        }

        protected void SetControlVisible(Control control, bool isVisible)
        {
            foreach (Control subControl in control.Controls)
            {
                if (subControl is System.Web.UI.WebControls.PlaceHolder || subControl is WF.Web.Controls.CCHRButton || subControl is System.Web.UI.WebControls.Button || subControl is System.Web.UI.ICheckBoxControl)
                {
                    subControl.Visible = isVisible;
                }
                else
                {
                    SetControlVisible(subControl, isVisible);
                }
            }
        }

        //如果超过允许期限，此函数就获取新的生效日期，否则返回null
        protected DateTime? GetNewValidate(TextBox txtAuditStatus, Label lblValidate)
        {
            DateTime? validate = null;
            //审批跨月延迟未审批的单据，人事部自由设定追单日期，在允许期限内审批通过的，按单上生效日生效，

            //在允许期限以后才审批通过的，生效日期为次月1日或者配置,现在是取自配置参数Validay
            //前提是，此单还未处理过,即审批状态为空，即flagaudit为0时，才进行上述处理          
            if (txtAuditStatus.Text == "")
            {
                WF.BusinessObject.SystemSetting sysSet = new BusinessObject.SystemSetting();
                string FinalAuditDay = sysSet.GetValueByParamName("FinalAuditDay");

                //判断配置的day是否为1到31号

                if (!IsValid(FinalAuditDay))
                {
                    throw new BusinessException("请设置正确的审批时间阀,其值只能为1-31号");
                }

                DateTime tempDate = Convert.ToDateTime(lblValidate.Text).AddMonths(1);
                string finalAuditDate = tempDate.Year + "-" + tempDate.Month + "-" + FinalAuditDay;

                DateTime CurrentDate = Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd"));
                if (Convert.ToDateTime(finalAuditDate) < CurrentDate)
                {
                    string Validay = sysSet.GetValueByParamName("Validay");
                    if (!IsValid(Validay))
                    {
                        throw new BusinessException("请设置正确的生效日，其值只能为1-31号");
                    }
                    validate = Convert.ToDateTime(CurrentDate.Year + "-" + CurrentDate.Month + "-" + Validay);
                }
            }
            return validate;
        }

        //检验是否有效日期中的天
        private bool IsValid(string str)
        {
            bool result = true;
            try
            {
                int num = int.Parse(str);
                if (num <= 0 || num > 31)
                    result = false;
            }
            catch
            {
                result = false;
            }
            return result;
        }
        #endregion
    }
}